﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using ERP.Common.DTO;
using ERP.Team.ProductionSystem;
using ERP.ERPSystem.ProductionSystem.Dto;

namespace ERP.ERPSystem.ProductionSystem
{
    /// <summary>
    /// 供应商服务实现类
    /// </summary>
    public class SupplierServer : ApplicationService, ISupplierServer
    {
        /// <summary>
        /// 供应商仓储接口（依赖注入）
        /// </summary>
        private readonly IRepository<Supplier, int> _supplierRepository;

        /// <summary>
        /// 构造函数注入仓储实例
        /// </summary>
        /// <param name="supplierRepository">供应商仓储接口</param>
        public SupplierServer(IRepository<Supplier, int> supplierRepository)
        {
            _supplierRepository = supplierRepository;
        }

        /// <summary>
        /// 分页查询供应商列表
        /// </summary>
        /// <param name="keyword">搜索关键词（供应商名称/编码）</param>
        /// <param name="isEnabled">是否启用状态（null表示不筛选）</param>
        /// <param name="page">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns>分页结果集</returns>
        public async Task<PagedResult<SupplierDTO>> GetPagedListAsync(string keyword = null, bool? isEnabled = null, int page = 1, int pageSize = 10)
        {
            // 获取可查询对象
            var queryable = await _supplierRepository.GetQueryableAsync();

            // 关键词筛选（名称或编码包含）
            if (!string.IsNullOrEmpty(keyword))
                queryable = queryable.Where(c => c.SupplierName.Contains(keyword) || c.SupplierCode.Contains(keyword));

            // 启用状态筛选（1=启用，0=禁用）
            if (isEnabled.HasValue)
                queryable = queryable.Where(c => c.IsNo == (isEnabled.Value ? 1 : 0));

            // 计算总记录数
            var total = queryable.Count();

            // 分页查询（按ID倒序）
            var data = queryable
                .OrderByDescending(c => c.Id)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            // 实体转DTO（数据传输对象）
            var dtoList = data.Select(x => new SupplierDTO
            {
                Id = x.Id,
                SupplierCode = x.SupplierCode,
                SupplierName = x.SupplierName,
                SupplierGrade = x.SupplierGrade,
                SupplierScore = x.SupplierScore,
                SupplierPhone = x.SupplierPhone,
                IsNo = x.IsNo,
                SupplierAdress = x.SupplierAdress,
                Context = x.Context
            }).ToList();

            // 返回分页结果
            return new PagedResult<SupplierDTO>
            {
                Total = total,
                Data = dtoList
            };
        }

        /// <summary>
        /// 根据ID获取供应商详情
        /// </summary>
        /// <param name="id">供应商ID</param>
        /// <returns>供应商DTO（不存在则返回null）</returns>
        public async Task<SupplierDTO> GetByIdAsync(int id)
        {
            // 查询实体
            var x = await _supplierRepository.GetAsync(y => y.Id == id);

            // 实体转DTO
            if (x == null) return null;
            return new SupplierDTO
            {
                Id = x.Id,
                SupplierCode = x.SupplierCode,
                SupplierName = x.SupplierName,
                SupplierGrade = x.SupplierGrade,
                SupplierScore = x.SupplierScore,
                SupplierPhone = x.SupplierPhone,
                IsNo = x.IsNo,
                SupplierAdress = x.SupplierAdress,
                Context = x.Context
            };
        }

        /// <summary>
        /// 保存供应商（新增或更新）
        /// </summary>
        /// <param name="entity">供应商DTO</param>
        /// <returns>操作是否成功</returns>
        public async Task<bool> SaveAsync(SupplierDTO entity)
        {
            // 新增逻辑（ID=0表示新增）
            if (entity.Id == 0)
            {
                // 创建新实体并赋值
                var model = new Supplier
                {
                    SupplierCode = entity.SupplierCode,
                    SupplierName = entity.SupplierName,
                    SupplierGrade = entity.SupplierGrade,
                    SupplierScore = entity.SupplierScore,
                    SupplierPhone = entity.SupplierPhone,
                    IsNo = entity.IsNo,
                    SupplierAdress = entity.SupplierAdress,
                    Context = entity.Context
                };

                // 插入并返回结果
                return await _supplierRepository.InsertAsync(model) != null;
            }
            // 更新逻辑
            else
            {
                // 查询现有实体
                var model = await _supplierRepository.GetAsync(entity.Id);
                if (model == null) return false;

                // 更新实体属性
                model.SupplierCode = entity.SupplierCode;
                model.SupplierName = entity.SupplierName;
                model.SupplierGrade = entity.SupplierGrade;
                model.SupplierScore = entity.SupplierScore;
                model.SupplierPhone = entity.SupplierPhone;
                model.IsNo = entity.IsNo;
                model.SupplierAdress = entity.SupplierAdress;
                model.Context = entity.Context;

                // 更新并返回结果
                return await _supplierRepository.UpdateAsync(model) != null;
            }
        }

        /// <summary>
        /// 根据ID删除供应商
        /// </summary>
        /// <param name="id">供应商ID</param>
        /// <returns>操作结果（始终返回true）</returns>
        public async Task<bool> DeleteAsync(int id)
        {
            await _supplierRepository.DeleteAsync(x => x.Id == id);
            return true;
        }

        /// <summary>
        /// 批量删除供应商
        /// </summary>
        /// <param name="ids">供应商ID列表</param>
        /// <returns>操作结果（始终返回true）</returns>
        public async Task<bool> DeleteBatchAsync(List<int> ids)
        {
            // 遍历删除（注意：此处为逐条删除，未使用批量操作）
            foreach (var id in ids)
            {
                await _supplierRepository.DeleteAsync(x => x.Id == id);
            }
            return true;
        }
    }
}
